import { useEffect, useState } from 'react'
import { Sun, Moon, Monitor } from 'lucide-react'
import { useLanguage } from '../contexts/LanguageContext'
import { t } from '../i18n/translations'

type Theme = 'light' | 'dark' | 'system'

export function ThemeToggle() {
  const { language } = useLanguage()
  const [theme, setTheme] = useState<Theme>(() => {
    const saved = localStorage.getItem('theme') as Theme
    return saved || 'system'
  })

  useEffect(() => {
    const applyTheme = (themeToApply: Theme) => {
      const root = window.document.documentElement
      
      if (themeToApply === 'system') {
        const systemTheme =
          typeof window !== 'undefined' &&
          typeof window.matchMedia === 'function' &&
          window.matchMedia('(prefers-color-scheme: dark)').matches
            ? 'dark'
            : 'light'
        root.classList.remove('light', 'dark')
        root.classList.add(systemTheme)
        root.removeAttribute('data-theme')
      } else {
        root.classList.remove('light', 'dark', 'system')
        root.classList.add(themeToApply)
        root.setAttribute('data-theme', themeToApply)
      }
    }

    applyTheme(theme)
  }, [theme])

  const cycleTheme = () => {
    setTheme(current => {
      switch (current) {
        case 'light': return 'dark'
        case 'dark': return 'system'
        case 'system': return 'light'
        default: return 'light'
      }
    })
  }

  const getThemeIcon = (themeType: Theme) => {
    switch (themeType) {
      case 'light': return <Sun className="w-4 h-4" />
      case 'dark': return <Moon className="w-4 h-4" />
      case 'system': return <Monitor className="w-4 h-4" />
      default: return <Sun className="w-4 h-4" />
    }
  }

  const getThemeLabel = (themeType: Theme) => {
    switch (themeType) {
      case 'light': return t('lightTheme', language)
      case 'dark': return t('darkTheme', language)
      case 'system': return t('systemTheme', language)
      default: return t('lightTheme', language)
    }
  }

  return (
    <div className="relative group">
      <button
        onClick={cycleTheme}
        className="btn-ghost group-hover:bg-primary-500/10 transition-all duration-200"
        title={getThemeLabel(theme)}
      >
        {getThemeIcon(theme)}
      </button>
      
      {/* Theme tooltip */}
      <div className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 px-3 py-2 bg-black/90 text-white text-sm rounded-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 pointer-events-none whitespace-nowrap">
        {getThemeLabel(theme)}
        <div className="absolute top-full left-1/2 transform -translate-x-1/2 w-2 h-2 bg-black/90 rotate-45"></div>
      </div>
    </div>
  )
}

export function ThemeSelector({ 
  value, 
  onChange 
}: { 
  value: Theme
  onChange: (theme: Theme) => void 
}) {
  const { language } = useLanguage()

  const themes = [
    { value: 'light' as Theme, label: t('lightTheme', language), icon: <Sun className="w-4 h-4" /> },
    { value: 'dark' as Theme, label: t('darkTheme', language), icon: <Moon className="w-4 h-4" /> },
    { value: 'system' as Theme, label: t('systemTheme', language), icon: <Monitor className="w-4 h-4" /> }
  ]

  return (
    <div className="space-y-2">
      <label className="text-sm font-medium text-text-secondary">
        {t('theme', language)}
      </label>
      <div className="grid grid-cols-3 gap-2">
        {themes.map(({ value: themeValue, label, icon }) => (
          <button
            key={themeValue}
            onClick={() => onChange(themeValue)}
            className={`p-3 rounded-lg border-2 transition-all duration-200 flex flex-col items-center gap-2 text-sm font-medium ${
              value === themeValue
                ? 'border-primary-500 bg-primary-500/10 text-primary-500'
                : 'border-panel-border bg-panel-bg text-text-secondary hover:border-primary-400 hover:text-primary-400'
            }`}
          >
            {icon}
            {label}
          </button>
        ))}
      </div>
    </div>
  )
}